const express = require('express');
const { handleError, executeQuery, formatDateTime } = require('../utils');
const router = express.Router();
const { checkExpiredLocks, checkExpiredLoans, addNextYearReservation } = require('../utils/schedule');
router.post('/updateFine', async (req, res) =>{
    const { fine_value } = req.body;
    const updateFineQuery = `
        UPDATE utils
        SET data_value=?
        WHERE utils_id=1;
    `;
    try {
        await executeQuery(updateFineQuery, [fine_value]);
        await checkExpiredLoans();
        res.json({ message: '罚款系数更新完成' });
    } catch (error) {
        handleError(error, res);
    }
});

router.post('/updateLockDay', async (req, res) =>{
    const { lock_day} = req.body;
    const updateFineQuery = `
        UPDATE utils
        SET data_value=?
        WHERE utils_id=2;
    `;
    try {
        await executeQuery(updateFineQuery, [lock_day]);
        await checkExpiredLocks();
        res.json({ message: '借阅锁定期更新完成' });
    } catch (error) {
        handleError(error, res);
    }
});

router.post('/updateNumOfMagzine', async (req, res) =>{
    const { NumOfMagazine } = req.body;
    // 校验 NumOfMagazine 是否是有效的数字
    if (typeof NumOfMagazine !== 'number' || NumOfMagazine < 0) {
        return res.status(400).json({ message: '期刊数量必须是一个非负数字' });
    }
    const updateFineQuery = `
        UPDATE utils
        SET data_value=?
        WHERE utils_id=3;
    `;
    try {
        await executeQuery(updateFineQuery, [NumOfMagazine]);
        await addNextYearReservation();
        res.json({ message: '热点借阅征订期刊数量更新完成' });
    } catch (error) {
        handleError(error, res);
    }
});

router.post('/updateStudentBorrowLimits', async (req, res) => {

    const {NumOfStudentBorrowLimits} = req.body;
    const updateStudentBorrowLimitQuery = `
        UPDATE utils
        SET data_value=?
        WHERE utils_id=4;
    `;

    const selectStudentBorrowLimits = `
        select data_value
        from utils
        where utils_id=4;
    `;

        
    const StudentBorrowLimitsRecord=await executeQuery(selectStudentBorrowLimits);
    const PastNumOfBorrowLimits = StudentBorrowLimitsRecord[0]?.data_value;

    const updateStudentsLimits = `
    update users
    set borrow_limit=${NumOfStudentBorrowLimits}
    where  role='student' 
        and borrow_limit!=0 ;
    `;

    try {
        await executeQuery(updateStudentBorrowLimitQuery, [NumOfStudentBorrowLimits]);
        await executeQuery(updateStudentsLimits);
        res.json({ message: '学生借阅上限修改完成！' });
    } catch (error) {
        handleError(error, res);
    }

});

router.post('/updateTeacherBorrowLimits', async (req, res) =>{

    const {NumOfTeacherBorrowLimits} = req.body;
    const updateTeacherBorrowLimitQuery = `
        UPDATE utils
        SET data_value=?
        WHERE utils_id=5;
    `;

    const selectTeacherBorrowLimits = `
    select data_value
    from utils
    where utils_id=5;
    `;

    const TeacherBorrowLimitsRecord=await executeQuery(selectTeacherBorrowLimits);
    const PastNumOfBorrowLimits = TeacherBorrowLimitsRecord[0]?.data_value;

    const updateTeachersLimits = `
    update users
    set borrow_limit=${NumOfTeacherBorrowLimits}
    where  role='teacher' 
        and borrow_limit!=0;
    `;
    
    try {
        await executeQuery(updateTeacherBorrowLimitQuery, [NumOfTeacherBorrowLimits]);
        await executeQuery(updateTeachersLimits);
        res.json({ message: '老师借阅上限修改完成！' });
    } catch (error) {
        handleError(error, res);
    }
});

router.get('/getSettings', async (req, res) => {
    const getSettingsQuery = `
        SELECT utils_id, data_value 
        FROM utils
        WHERE utils_id BETWEEN 1 AND 5;
    `;
    try {
        const results = await executeQuery(getSettingsQuery);

        // 检查结果是否为空
        if (!results || results.length === 0) {
            return res.status(404).json({ message: '未找到任何设置项' });
        }

        // 格式化返回值
        const settings = {
            fine_value: results.find(item => item.utils_id === 1)?.data_value || 0,
            lock_day: results.find(item => item.utils_id === 2)?.data_value || 0,
            num_of_magazine: results.find(item => item.utils_id === 3)?.data_value || 0,
            NumOfStudentBorrowLimits: results.find(item => item.utils_id === 4)?.data_value || 0,
            NumOfTeacherBorrowLimits: results.find(item => item.utils_id === 5)?.data_value || 0,
        };

        res.json(settings);
    } catch (error) {
        console.error('获取设置失败：', error); // 打印详细错误日志
        handleError(error, res); // 统一错误处理
    }
});



module.exports = router;
